/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    // 法一：DFS
    // int maxDepth(TreeNode* root) {
    //     if (!root) return 0;
    //     int left = maxDepth(root->left);
    //     int right = maxDepth(root->right);
    //     if (left > right) return left + 1;
    //     else return right + 1;
    // }

    // 法二：BFS
    int maxDepth(TreeNode* root) {
        if (!root) return 0;
        queue<TreeNode*> q;
        q.push(root);
        int deep = 0;
        while (!q.empty()) {
            int len = q.size();
            deep++;
            for (int i = 0; i < len; ++i) {
                TreeNode* tmp = q.front();
                q.pop();
                if (tmp->left) q.push(tmp->left);
                if (tmp->right) q.push(tmp->right);
            }
        }
        return deep;
    }
};

// BFS
class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (!root) return 0;
        queue<pair<TreeNode*, int>> q;
        q.emplace(root, 1);
        int maxHeight = 0;
        while (!q.empty()) {
            TreeNode* node;
            int val;
            tie(node, val) = q.front();
            q.pop();
            if (!node->left && !node->right) maxHeight = max(maxHeight, val);
            if (node->left) q.emplace(node->left, val + 1);
            if (node->right) q.emplace(node->right, val + 1);
        }
        return maxHeight;
    }
};